/*
 * AGENT SHERPA
 *  
 * Assignement 2 of the Agent Oriented Software Engineering Course
 * M.Sc. in Advanced Software Engineering (Part-time)
 * University College Dublin www.ucd.ie
 *
 * Copyright (c) 2007 Chris Walsh, Aidan Morrisy and Iain Hull.
 * All rights reserved.
 */

package org.agentsherpa;

import org.agentsherpa.model.Direction;

import com.agentfactory.platform.interfaces.Actuator;
import com.agentfactory.platform.logic.FOS;

/**
 * Moves the agent one cell in the to in the desired direction
 */
public class MoveActuator extends Actuator {
    public boolean act(FOS action) {
        try {
            Direction direction = getDirection(action);
            SimulatorService simulator = getSimulator();

            simulator.move(this.agent, direction);
            return true;
        }
        catch (ActuatorException e) {
            System.err.println("MoveActuator error: " + e);
            return false;
        }
    }

    private SimulatorService getSimulator() throws ActuatorException {
        SimulatorService simulator = (SimulatorService) getService("org.agentsherpa.SimulatorService");
        if (simulator == null) {
            throw new ActuatorException("Cannot access SimulatorService");
        }
        return simulator;
    }

    private Direction getDirection(FOS action) throws ActuatorException {
        try {
            return Direction.valueOfIgnoreCase(action.getArguments().get(0)
                    .toString());
        }
        catch (IllegalArgumentException e) {
            throw new ActuatorException("Cannot resolve direction "
                    + action.getArguments().get(0).toString());
        }
    }
}
